package com.atguigu.flink0922.chapter05.sink;

import com.atguigu.flink0922.bean.WaterSensor;
import org.apache.flink.api.common.functions.RuntimeContext;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkFunction;
import org.apache.flink.streaming.connectors.elasticsearch.RequestIndexer;
import org.apache.flink.streaming.connectors.elasticsearch6.ElasticsearchSink;
import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.Requests;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/3/3 10:26
 */
public class Flink03_Sink_ES {
    public static void main(String[] args) {
        ArrayList<WaterSensor> waterSensors = new ArrayList<>();
        waterSensors.add(new WaterSensor("sensor_1", 1607527992000L, 20));
        waterSensors.add(new WaterSensor("sensor_1", 1607527994000L, 50));
        waterSensors.add(new WaterSensor("sensor_1", 1607527996000L, 50));
        waterSensors.add(new WaterSensor("sensor_2", 1607527993000L, 10));
        waterSensors.add(new WaterSensor("sensor_2", 1607527995000L, 30));
        
        final ArrayList<HttpHost> hosts = new ArrayList<>();
        hosts.add(new HttpHost("hadoop162", 9200));
        hosts.add(new HttpHost("hadoop163", 9200));
        hosts.add(new HttpHost("hadoop164", 9200));
        
        final ElasticsearchSink.Builder<WaterSensor> esBuilder = new ElasticsearchSink.Builder<>(
            hosts,
            new ElasticsearchSinkFunction<WaterSensor>() {
                @Override
                public void process(WaterSensor element,
                                    RuntimeContext ctx,
                                    RequestIndexer indexer) {
                    final HashMap<String, Object> data = new HashMap<>();
                    data.put("id", element.getId());
                    data.put("ts", element.getTs());
                    data.put("vc", element.getVc());
    
                    // 拿到每个元素, 对元素进行处理(写入到es中)
                    final IndexRequest index = Requests
                        .indexRequest()
                        .index("sensor")
                        .type("_doc")
                        .id(element.getId() + "_" + element.getTs())
//                        .source(JSON.toJSONString(element), XContentType.JSON);  // 推荐这种
                        .source(data);
                    
                    indexer.add(index);
                }
            });
        
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(2);
        env
            .fromCollection(waterSensors)
            .addSink(esBuilder.build());
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
        
    }
}
